package registration;

import java.lang.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import OnlineExam.db.*;
import static OnlineExam.configuration.Configure.*;

/**
 *   Handles the regisrtation of a user for an application.
 */

public final class RegistrationAction extends Action
{

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
					HttpServletResponse response)
	{
			
		User user = (User) form;
		
		// Delete the all unconfirmed users from the database who have their time limit expired.
		//
		// this function will be converted to a demon .
		
		deleteUnconfirmedUsers();	

			
		if (insertUnconfirmedUser(user))
   			return (mapping.findForward("success"));
		else
			return (mapping.findForward("error"));
  	}

	
	/**
	 *  Inserts the user information into the database and sets the users status as unconfirmed.
	 */
	
	
	public boolean insertUnconfirmedUser (User user) 
	{
			
		Session session = null;
		
		MailConfirmation confirm = new MailConfirmation ();
		long mailSentTime = confirm.sendMail (user.getEmailId());

		user.setJoinTime(mailSentTime);
		user.setStatus("unconfirmed");
		try
		{
			DBUtil.insert (user);
			return true;
		}
		catch (DBException e)
		{
			e.printStackTrace();
			return false;
		}
	}


	/**
	 *  deletes the unconfirmed users whose time limit has expired
	 *  will be converted to a demon process
	 */
	

	public void  deleteUnconfirmedUsers()
	{
		long currTime = System.currentTimeMillis ();
		long expTime = currTime - EXPIRY_TIME;
		
		Session session = null;
		
		try
		{
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
       		session = sessionFactory.openSession();
		
			String queryToDelete = "delete from User where Status = 'unconfirmed' and JoinTime < :expTime ";
        	Query query = session.createQuery(queryToDelete);
			
        	query.setLong("expTime",expTime);
			query.executeUpdate();
		}
		catch (HibernateException e)
		{
			System.out.println("Exception.." + e);
		}
		finally
		{
			try { if (session != null) session.flush(); session.close();}
			catch (Exception e) { System.out.println ("Exception.." + e);}
		}
	}
}
